package com.union.core.sys.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.union.core.organization.dao.impl.PersonnelDaoImpl;
import com.union.core.organization.model.Personnel;
import com.union.core.sys.dao.SysManagerDao;
import com.union.core.sys.dao.SysModuleDao;
import com.union.core.sys.dao.SysModuleTypeDao;

import com.union.core.sys.dao.impl.RoleDaoImpl;
import com.union.core.sys.dao.impl.SysManagerDaoImpl;
import com.union.core.sys.dao.impl.SysModuleDaoImpl;
import com.union.core.sys.dao.impl.SysModuleTypeDaoImpl;

import com.union.core.sys.model.Role;
import com.union.core.sys.model.SysManager;
import com.union.core.sys.model.SysManagerSessionList;
import com.union.core.sys.model.SysModule;
import com.union.core.sys.model.SysModuleType;

/**
 * 业务逻辑处理类:系统帐号管理
 * filename: SysManagerService.java
 * project:  CCTR
 * @company Hainan Jowe Technology Ltd
 * @author wangxiuwu
 * @create in 2009-6-1
 * @version 1.0
 */
public class SysManagerService {
	private static Logger log = Logger.getLogger(SysManagerService.class.getName());
	private SysService sysService = SysService.getInstance();
	
	private SysManagerDao sysManagerDaoImpl;
	private SysModuleTypeDao sysModuleTypeDaoImpl;
	private SysModuleDao sysModuleDaoImpl;
	private PersonnelDaoImpl personnelDaoImpl;
	//角色表
	private RoleDaoImpl roleDI;
	private RoleService roleSer;
	private Role role;
	public SysManagerService() {
		sysModuleTypeDaoImpl = new SysModuleTypeDaoImpl();
		sysModuleDaoImpl = new SysModuleDaoImpl();
		sysManagerDaoImpl = new SysManagerDaoImpl();
		roleDI=new RoleDaoImpl();
		personnelDaoImpl=new PersonnelDaoImpl();
		roleSer=new RoleService();
	}
	
	/**
	 * 添加加载
	 * @return List<SysModuleType>
	 */
	public List<SysModuleType> addload(){
		
		/*取得模块类别*/
		List<SysModuleType> sysModuleTypeList = sysModuleTypeDaoImpl.getModuleTypeList(1);
		for(int i=0;i<sysModuleTypeList.size();i++){
			/*取得各类别小模块*/
			SysModuleType sysModuleType = (SysModuleType)sysModuleTypeList.get(i);
			List<SysModule> sysModuleList = sysModuleDaoImpl.getModuleList(1,2,sysModuleType.getMODULE_TYPE_ID());
			sysModuleType.setSysModuleList(sysModuleList);
			sysModuleTypeList.set(i, sysModuleType);
		}
		return sysModuleTypeList;
	}
	
	/**
	 * 修改加载
	 * @return List<SysModuleType>
	 */
	public List<SysModuleType> editload(String MODULE_MGR_PURVIEW,int ifShow){

		List<String> sysModuleIdList = sysManagerDaoImpl.getModuleMgrPurviewList(MODULE_MGR_PURVIEW);
		
		/*取得模块类别*/
		List<SysModuleType> sysModuleTypeList = sysModuleTypeDaoImpl.getModuleTypeList(1);
		List<SysModuleType> sysModuleTypeList1=new ArrayList<SysModuleType>();
		for(int i=0;i<sysModuleTypeList.size();i++){
			/*取得各类别小模块*/
			SysModuleType sysModuleType = (SysModuleType)sysModuleTypeList.get(i);
			
			List<SysModule> sysModuleList = sysModuleDaoImpl.getModuleList(1,ifShow,sysModuleType.getMODULE_TYPE_ID());
			List<SysModule> sysModuleList1= new ArrayList<SysModule>();
			for(int j=0;j<sysModuleList.size();j++){
				String sysModuleIdTemp = null;
				for(int s=0;s<sysModuleIdList.size();s++){
					sysModuleIdTemp = (String)sysModuleIdList.get(s);
					if(sysModuleIdTemp!=null){
							if((String.valueOf(sysModuleList.get(j).getMODULE_ID())).equals(sysModuleIdTemp)){
								sysModuleList1.add(sysModuleList.get(j));
							}
					}
				}
			}
			if(sysModuleList1.size()>0){
				sysModuleType.setSysModuleList(sysModuleList1);
				sysModuleTypeList1.add(sysModuleType);
			}
		}
		return sysModuleTypeList1;
	}
	
	/**
	 * 登陆系统
	 * @param LOGIN_NAME
	 * @param LOGIN_PWD
	 * @param randCode
	 * @return
	 */
	public String sysManagerLogin(String LOGIN_NAME, String LOGIN_PWD, String randCode){
		String loginResult;
		
		/*验证码校验*/
    	boolean isResponseCorrect = sysService.checkRandCode(randCode);
		//boolean isResponseCorrect = true;
    	if(isResponseCorrect==true){ /*验证码正确,开始帐号和密码校验*/
    		boolean ifexist = SysManagerSessionList.getInstance().existMgrSession(LOGIN_NAME);
        	
        	//已经在线，踢下线，重新登陆
        	if(ifexist==true){
        		HttpSession mgrSession = SysManagerSessionList.getInstance().getMgrSession(LOGIN_NAME);
        		if(null != mgrSession){
        			SysManagerSessionList.getInstance().removeSession(mgrSession); //踢下线
        		}
        	}

        	try{
				SysManager sysManager = sysManagerDaoImpl.login(LOGIN_NAME, LOGIN_PWD);
				
				if(sysManager!=null){
					
					/*记录登陆信息*/
					int ManagerId = sysManager.getMANAGER_ID();
					int LoginTimes = sysManager.getLOGIN_TIMES();	
					
					//获取登陆客户端IP地址
					String LastLoginIp = sysService.getIpAddr(ServletActionContext.getRequest());
					
					sysManagerDaoImpl.modifyManager(ManagerId,LoginTimes+1,LastLoginIp);
					//获取账号对应人员信息
					int personnelId=sysManager.getPERSONNEL_ID();
					if(personnelId!=0){
						Personnel person=personnelDaoImpl.query(personnelId);
						sysManager.setPERSONNEL(person);
					}else{
						Personnel person=new Personnel();
						person.setPersonnel_name("System");
						person.setOrganization_name("海口总工会");
						person.setPersonnel_position("信息管理员");
						person.setOrganization_id(1);
						sysManager.setPERSONNEL(person);
					}
					List<String> power=getLoginPower(sysManager.getMODULE_MGR_PURVIEW(),sysManager.getMANAGER_ROLES());
					sysManager.setAllPower(power);
					/*设置后台系统登陆session信息*/
					sysManager.setMANAGER_PWD(LOGIN_PWD);    //改变密码为明文
					sysService.setSessionListener(sysManager);
					
					loginResult = "登陆成功";
					log.info("系统登陆:[user="+LOGIN_NAME+",IP="+LastLoginIp+"] "+loginResult);
				}else{
					loginResult = "[提示信息] 帐号或密码不正确!"; //登陆失败：帐号或密码不正确
					log.info("系统登陆: ["+LOGIN_NAME+"] "+loginResult);
				}	
			}catch(Exception ex){
				loginResult = "[提示信息] 系统错误!"; //登陆失败：系统错误
				log.info("系统登陆: ["+LOGIN_NAME+"] "+loginResult + ": "+ex);
			}
				
		}else{
			loginResult = "[提示信息] 验证码错误!"; //登陆失败：验证码错误
			log.info("系统登陆: ["+LOGIN_NAME+"] "+loginResult);
		}
		
		
		return loginResult;
		
	}
	
	
	public List<SysManager> queryAll(){
		List<SysManager> SysManagers = sysManagerDaoImpl.getManagerList();

		for(int i=0; i<SysManagers.size(); i++){
			if(SysManagerSessionList.getInstance().existMgrSession(SysManagers.get(i).getMANAGER_NAME())){
				SysManagers.get(i).setOnline_flag(true);  //在线
			}else{
				SysManagers.get(i).setOnline_flag(false); //离线
			}
		}
		
		log.info("查询系统帐号列表");
		return SysManagers;
	}
	
	public SysManager querySysManager(int managerId){
		SysManager sysManager = sysManagerDaoImpl.getManager(managerId);
		log.info("提取帐号信息: "+sysManager.getMANAGER_ID()+":"+sysManager.getMANAGER_NAME());
		return sysManager;
	}
	
	public void addSysManager(SysManager sysManager,String[] moduleMgrPurview){
		
		String MODULE_MGR_PURVIEW = "|";
		if(moduleMgrPurview!=null){
			for(int i=0;i < moduleMgrPurview.length;i++){
				MODULE_MGR_PURVIEW = MODULE_MGR_PURVIEW + moduleMgrPurview[i] + "|";
			}
		}
		sysManager.setMODULE_MGR_PURVIEW(MODULE_MGR_PURVIEW);
		if(sysManager.getMANAGER_PWD()==null){
			sysManager.setMANAGER_PWD("123456");
		}else{
			sysManager.setMANAGER_PWD(sysManager.getMANAGER_PWD().trim());
			if(sysManager.getMANAGER_PWD().equals("")) sysManager.setMANAGER_PWD("123456");
		}
		sysManagerDaoImpl.addManager(sysManager);
		log.info("添加帐号: "+sysManager.getMANAGER_ID()+":"+sysManager.getMANAGER_NAME());
	}
	public int accountAllot(SysManager sysManager){
		boolean bl=false;
		int id=0;
		if(sysManager.getMANAGER_PWD()==null){
			sysManager.setMANAGER_PWD("123456");
		}else{
			sysManager.setMANAGER_PWD(sysManager.getMANAGER_PWD().trim());
			if(sysManager.getMANAGER_PWD().equals("")) sysManager.setMANAGER_PWD("123456");
		}
		bl=sysManagerDaoImpl.addManager(sysManager);
		if(bl){
			id=sysManagerDaoImpl.getManagerId(sysManager.getMANAGER_NAME());
		}
		log.info("添加帐号: "+id+":"+sysManager.getMANAGER_NAME());
		return id;
	}
	public void modifySysManager(SysManager sysManager,String[] moduleMgrPurview){
		String MODULE_MGR_PURVIEW = "|";
		if(moduleMgrPurview!=null){
			for(int i=0;i < moduleMgrPurview.length;i++){
				MODULE_MGR_PURVIEW = MODULE_MGR_PURVIEW + moduleMgrPurview[i] + "|";
			}
		}
		sysManager.setMODULE_MGR_PURVIEW(MODULE_MGR_PURVIEW);
		if(sysManager.getMANAGER_PWD()==null){
			sysManager.setMANAGER_PWD("123456");
		}else{
			sysManager.setMANAGER_PWD(sysManager.getMANAGER_PWD().trim());
			if(sysManager.getMANAGER_PWD().equals("")) sysManager.setMANAGER_PWD("123456");
		} 
		sysManagerDaoImpl.modifyManager(sysManager);
		log.info("修改帐号: "+sysManager.getMANAGER_ID()+":"+sysManager.getMANAGER_NAME());
	}
	
	public void deleteSysManager(int managerId){
		sysManagerDaoImpl.deleteManager(managerId);
		log.info("删除帐号: "+managerId);
	}
	
	public void modifySysManagerSTATUS(int managerId, int status){
		sysManagerDaoImpl.modifyManager(managerId, status);
		log.info("修改帐号状态: "+managerId+":"+status);
	}
	
	public void resetPwd(int managerId, String managerName, String newPwd){
		sysManagerDaoImpl.modifyPasswd(managerId,managerName,newPwd);
		log.info("重置密码: "+managerId+":"+newPwd);
	}
	//修改账号密码
	public String modifySysUser(int Managerid,String User_logcontain,String Password){

		String modifyLogPwd;
		//账号校验
		/*if(User_logcontain == "" && User_log == "" && Password == ""){
			modifyLogPwd = "错误：账号不能为空";
		}else{
			if(User_logcontain.equals(User_log) ){
				System.out.println("User_logcontain" + User_logcontain);
				//输入的账号已存在
				modifyLogPwd = "错误：账号已经存在";
			}else{*/
				if( "".equals(User_logcontain)){
					modifyLogPwd ="错误:新账户不能为空";
				}else
					if(  "".equals(Password)){
					//密码不能为空
					modifyLogPwd = "错误：新密码不能为空";
					System.out.println("Password" + Password);
				}else{
					//执行账号密码修改
					boolean result = sysManagerDaoImpl.modifyuserManager(Managerid,User_logcontain,Password);
					personnelDaoImpl.edit1(Managerid, User_logcontain);
					if(result == true){
						modifyLogPwd = "账号密码修改成功！新密码是：" + Password + "新账号是:" + User_logcontain;
					}else{
						 modifyLogPwd = "错误：账户密码修改失败";
					}
				}
				System.out.println(modifyLogPwd);
				return modifyLogPwd;
			}
//		}	
		
//	}
	
	public String modifySysManagerPWD(int ManagerId,String PWD_OLD,String PWD_NEW,String PWD_NEW_CFM){
	
		String ManagerName = sysService.getSessionListener().getMANAGER_NAME();
		String ManagerPwd = sysService.getSessionListener().getMANAGER_PWD();
		String modifyPwdResult;
	
		
		//旧密码校验
		if(!PWD_OLD.equals(ManagerPwd)){
			//输入的旧密码错误
			modifyPwdResult = "错误：输入的旧密码错误";
		}else{
			if(!PWD_NEW_CFM.equals(PWD_NEW)){
				//新密码与确认新密码不吻合
				modifyPwdResult = "错误：输入的新密码与确认新密码不吻合";
			}else{
				//#执行密码修改#
				boolean result = sysManagerDaoImpl.modifyPasswd(ManagerId,ManagerName,PWD_NEW);
				if(result==true){
					modifyPwdResult = "密码修改成功! 新密码是:"+PWD_NEW;
					
					sysService.getSessionListener().setMANAGER_PWD(PWD_NEW);
					
				}else{
					modifyPwdResult = "错误：密码修改失败";
				}
			}
		}		
		System.out.println(modifyPwdResult);
		return modifyPwdResult;
	}
	
	/**
	 * 获取在线人数
	 * @return int
	 */
	public int getOnlineUserCount(){
		return SysManagerSessionList.getInstance().getSessionCount();
	}
	/**
	 * 获取账户角色表
	 * */
	public List<Role> getRoles(SysManager sysManager,int orgId){
		List<Role> roles=new ArrayList<Role>();
		List<Role> managerRoles=new ArrayList<Role>();
		List<String> roleIds=new ArrayList<String>();
		//获取被授予角色的账号已有的角色列表
		if(sysManager.getMANAGER_ROLES()!=null && !"".equals(sysManager.getMANAGER_ROLES())){
			roleIds=sysManagerDaoImpl.getModuleMgrPurviewList(sysManager.getMANAGER_ROLES());
		}
		//查询出登录账号可赋予的角色列表遍历
		roles=roleDI.queryRoleList(0, null, null, null, null,0,orgId, null, null, 0, 200);
		for(Role role : roles){
				if(roleIds.size()!=0){
					//遍历账号已经拥有的角色ID将对应的角色选中
					for(String roleId : roleIds){
						if(String.valueOf(role.getId()).equals(roleId)){
							role.setIfchecked(1);
						}
					}
				}
				managerRoles.add(role);
			
		}
		return managerRoles;
	}
	/*
	 * 赋予角色
	 * */
	public boolean setRoles(SysManager sysManager,String[] roleIds){
		boolean bl=false;
		String MANAGER_ROLES = "|";
		if(roleIds!=null){
			for(String roleId : roleIds){
				MANAGER_ROLES = MANAGER_ROLES + roleId + "|";
			}
			sysManager.setMANAGER_ROLES(MANAGER_ROLES);
			
		}
		if(sysManager.getMODULE_MGR_PURVIEW()==null){
			sysManager.setMODULE_MGR_PURVIEW("");
		}
		bl=sysManagerDaoImpl.modifyManager(sysManager);
		return bl;
	}
	/*
	 *返回登录用户权限数组 
	 * */
	private List<String> getLoginPower(String modulePower,String roleIds){

		//角色权限
			//整合角色权限
			Set<String> set = new HashSet<String>();
			
			if(roleIds!=null && !"".equals(roleIds)){
				for(String rid : roleIds.split("\\|")){
					if(!"".equals(rid)){
					role=roleSer.queryById(Integer.parseInt(rid));
					String rpu=role.getRole_permissions();
					if(rpu!=null && !"".equals(rpu)){
						for(String pu : rpu.split("\\|")){
							if(!"".equals(pu)){
								set.add(pu);
							}
						}
					}
				}
				}
			}
			String abc="|";
			//整合用户与角色权限
			if(modulePower!=null && !"".equals(modulePower)){
				for(String pu : modulePower.split("\\|")){
						if(!"".equals(pu)){
							set.add(pu);
						}
					}
			}
			//返回权限
	        for(Object s: set.toArray()){
	        	abc=abc+s.toString()+"|";
	        }
		List<String> logPower=sysManagerDaoImpl.getModuleMgrPurviewList(abc);;
		return logPower;
	}
	/*
	 * 加载账号授权
	 * 
	 * */
	public List<SysModuleType> editload(int managerId,String MODULE_MGR_PURVIEW){
		System.out.println("错误？");
		String pulist=sysManagerDaoImpl.getManager(managerId).getMODULE_MGR_PURVIEW();
		List<String> sysModuleIdList=new ArrayList<String>();
		if(pulist!=null&&!"".equals(pulist)){
			sysModuleIdList = sysManagerDaoImpl.getModuleMgrPurviewList(pulist);
		}
		List<String> sysModuleIdList1 = sysManagerDaoImpl.getModuleMgrPurviewList(MODULE_MGR_PURVIEW);
		/*取得模块类别*/
		List<SysModuleType> sysModuleTypeList = sysModuleTypeDaoImpl.getModuleTypeList(1);
		List<SysModuleType> sysModuleTypeList1=new ArrayList<SysModuleType>();
		for(int i=0;i<sysModuleTypeList.size();i++){//遍历所有模块类型
			/*取得各类别小模块*/
			SysModuleType sysModuleType = (SysModuleType)sysModuleTypeList.get(i);
			List<SysModule> sysModuleList = sysModuleDaoImpl.getModuleList(1,2,sysModuleType.getMODULE_TYPE_ID());
			List<SysModule> sysModuleList1=new ArrayList<SysModule>();
			for(int j=0;j<sysModuleList.size();j++){//遍历第i个模块里的所有子模块
				String sysModuleIdTemp = null;
				for(int s=0;s<sysModuleIdList1.size();s++){//遍历用户权限中的模块ID
					sysModuleIdTemp = (String)sysModuleIdList1.get(s);
					if(sysModuleIdTemp!=null){
							//从所有子模块中取得用户拥有权限的子模块
							if((String.valueOf(sysModuleList.get(j).getMODULE_ID())).equals(sysModuleIdTemp)){
								for(int b=0;b<sysModuleIdList.size();b++){//遍历选中账号拥有权限的模块ID
									String sysModuleIdrole=(String)sysModuleIdList.get(b);
									if(sysModuleIdrole.equals(sysModuleIdTemp)){
										sysModuleList.get(j).setIfchecked(1);//从用户的子模中将角色的子模设置为选中
									}
								}
								sysModuleList1.add(sysModuleList.get(j));
								
							}
					}
				}
				
			}
			if(sysModuleList1.size()!=0){
				sysModuleType.setSysModuleList(sysModuleList1);
				sysModuleTypeList1.add(sysModuleType);
			}
			
		}
		log.info("加载账号赋权");
		return sysModuleTypeList1;
	}
	public boolean empower(SysManager sysManager,String[] MODULE_MGR_PURVIEW){
		boolean bl=false;
		String managerPermissions="";
		if(MODULE_MGR_PURVIEW.length!=0 && MODULE_MGR_PURVIEW!=null){
			managerPermissions="|";
			for(String s : MODULE_MGR_PURVIEW){
				managerPermissions=managerPermissions+s+"|";
			}
			sysManager.setMODULE_MGR_PURVIEW(managerPermissions);
		}
		bl=sysManagerDaoImpl.modifyManager(sysManager);
		log.info("为账号赋权");
		return bl;
	}
	/**
	 * 校验登陆用户帐号是否已存在
	 * @param loginName String
	 * @return boolean
	 * false-无记录 true-有记录
	 */
	public boolean checkLoginName(String loginName){
		log.info("PLAT: 校验客户(买家)登陆用户帐号是否已存在: "+loginName);
		return sysManagerDaoImpl.checkLoginName(loginName);
	}
}
